package cm.kafka.configuration;

/**
 * @author LiuWei
 * @description 线程池配置
 * @date 2019/6/18
 */

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ExecutorConfig {

    //获取当前机器的核数
    public static final int cpuNum = Runtime.getRuntime().availableProcessors();

    @Bean
    public ThreadPoolTaskExecutor getExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(cpuNum * 2);//核心线程大小
        taskExecutor.setMaxPoolSize(cpuNum * 4);//最大线程大小
        taskExecutor.setQueueCapacity(1000);//队列最大容量
        //当提交的任务个数大于QueueCapacity，就需要设置该参数，但spring提供的都不太满足业务场景，可以自定义一个，也可以注意不要超过QueueCapacity即可
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        taskExecutor.setAwaitTerminationSeconds(60);
        taskExecutor.setThreadNamePrefix("lcs-tsalog-Thread-");
        taskExecutor.initialize();
        return taskExecutor;
    }

}

